﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.Rendering;
using NetCoreCMS.Common;
using NetCoreCMS.IServices;
using NetCoreCMS.Models;

namespace NetCoreCMS.Web.Areas.Admin.Controllers
{
    public class Article_EditController : ManageController
    {
        private const string WEB_VIEW = "~/Areas/Admin/Views/Article/article_edit.cshtml";
        private string action = CMSEnums.ActionEnum.Add.ToString(); //操作类型
        private int id = 0;
        private string error = string.Empty;
        protected int channel_id;
        protected string prolistview = string.Empty;
        public IArticleService _article { get; set; }
        public IArticle_categoryService _article_category { get; set; }
        public IArticle_goods_specService _article_goods_spec { get; set; }
        public IShopService _shop { get; set; }
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            base.OnActionExecuting(filterContext);
            if (filterContext.Result != null)
                return;
            ActionResult result = View(EDIT_RESULT_VIEW);
            this.channel_id = CMSRequest.GetQueryInt("channel_id", filterContext.HttpContext);
            action = Request.Query["action"];
            this.prolistview = Request.Query["prolistview"];
            if (this.prolistview != null)
            {
                Response.Cookies.Append("article_list_view", this.prolistview);
            }
            else
            {
                this.prolistview = Request.Cookies["article_list_view"]; //显示方式
                if (this.prolistview == "")
                    this.prolistview = "Txt";
            }

            //如果是编辑或复制则检查信息是否存在
            if (action == CMSEnums.ActionEnum.Edit.ToString() || action == CMSEnums.ActionEnum.Copy.ToString() || action == CMSEnums.ActionEnum.View.ToString())
            {
                int.TryParse(Request.Query["id"], out this.id);
                if (this.id == 0)
                {
                    JscriptMsg("传输参数不正确！", "back");
                    filterContext.Result = result;
                    return;
                }
                if (!_article.Exists(this.id))
                {
                    JscriptMsg("信息不存在或已被删除！", "back");
                    filterContext.Result = result;
                    return;
                }
            }
            //保存参数
            ViewBag.ChannelId = this.channel_id.ToString();
            ViewBag.Action = this.action;
            ViewBag.Id = this.id.ToString();
            ViewBag.ProListView = this.prolistview;
        }

        // GET: /admin/Article_Edit/
        public ActionResult Index()
        {
            ChkAdminLevel("article_" + this.channel_id + "_list", CMSEnums.ActionEnum.View.ToString()); //检查权限
            TreeBind(); //绑定类别
            if (action == CMSEnums.ActionEnum.Edit.ToString())
            {
                ShowInfo(this.id);
            }
            else
            {
                NetCoreCMS.Models.Article model = new NetCoreCMS.Models.Article();
                model.sort_id = 99;
                ViewData["model"] = model;
            }
            return View(WEB_VIEW);
        }

        [HttpPost]
        public async Task<ActionResult> SubmitSave(string txtContent)
        {
            ActionResult result = View(EDIT_RESULT_VIEW);
            if (action == CMSEnums.ActionEnum.Edit.ToString()) //修改
            {
                ChkAdminLevel("article_" + this.channel_id + "_list", CMSEnums.ActionEnum.Edit.ToString()); //检查权限
                if (!await DoEdit(this.id, txtContent))
                {
                    JscriptMsg("保存过程中发生错误啦！", error);
                    return result;
                }
                JscriptMsg("修改信息成功！", "../article_list/index?channel_id=" + this.channel_id);
            }
            else //添加
            {
                ChkAdminLevel("article_" + this.channel_id + "_list", CMSEnums.ActionEnum.Add.ToString()); //检查权限
                if (!await DoAdd(txtContent))
                {
                    JscriptMsg("保存过程中发生错误！", error);
                    return result;
                }
                JscriptMsg("添加信息成功！", "../article_list/index?channel_id=" + this.channel_id);
            }
            return result;
        }

        #region 绑定类别=================================
        private void TreeBind()
        {
            var dt = _article_category.GetList(0, this.channel_id);
            List<SelectListItem> categoryList = new List<SelectListItem>() {
             new SelectListItem(){ Text="请选择类别...", Value=""}
          };
            foreach (Article_category dr in dt)
            {
                string Id = dr.id.ToString();
                int ClassLayer = dr.class_layer;
                string Title = dr.title;

                if (ClassLayer == 1)
                {
                    categoryList.Add(new SelectListItem() { Text = Title, Value = Id });
                }
                else
                {
                    Title = "├ " + Title;
                    Title = Utils.StringOfChar(ClassLayer - 1, "　") + Title;
                    categoryList.Add(new SelectListItem() { Text = Title, Value = Id });
                }
            }
            ViewData["categoryList"] = categoryList;
            //供货商
            var dt2 = _shop.GetList(1, 100, "where is_pass=1 and is_lock=0 and is_supply=1 and is_top=1", "sort_id desc");
            List<SelectListItem> shopList = new List<SelectListItem>() {
             new SelectListItem(){ Text="默认系统", Value="0"}
          };
            foreach (Shop dr in dt2)
            {
                shopList.Add(new SelectListItem() { Text = dr.shopname, Value = dr.id.ToString() });
            }
            ViewData["shopList"] = shopList;
        }
        #endregion

        #region 赋值操作=================================
        private void ShowInfo(int _id)
        {
            NetCoreCMS.Models.Article model = _article.GetModel(_id);
            ViewData["model"] = model;
            
            //商品规格赋值
            List<Article_goods_spec> goodsSpecList = _article_goods_spec.GetList(model.id, "");
            ViewBag.GoodsSpecJson = JsonHelper.ObjectToJSON(goodsSpecList);
            //绑定图片相册
            if (!string.IsNullOrEmpty(model.img_url))
            {
                string filename = model.img_url.Substring(model.img_url.LastIndexOf("/") + 1);
                if (filename.StartsWith("thumb_"))
                {
                    ViewBag.hidFocusPhoto = model.img_url; //封面图片
                }
            }
        }
        #endregion

        #region 保存远程图片到本地=======================
        private string AutoRemoteImageSave(string content)
        {
            if (string.IsNullOrEmpty(content))
            {
                return string.Empty;
            }
            Common.UpLoad upload = new Common.UpLoad(_env.WebRootPath, sysConfig);
            Regex reg = new Regex("IMG[^>]*?src\\s*=\\s*(?:\"(?<1>[^\"]*)\"|'(?<1>[^\']*)')", RegexOptions.IgnoreCase);
            MatchCollection m = reg.Matches(content);
            foreach (Match math in m)
            {
                string imgUri = math.Groups[1].Value;
                if (imgUri.StartsWith("https"))
                {
                    string newImgPath = upload.RemoteSaveAs(imgUri);
                    if (newImgPath != string.Empty)
                    {
                        content = content.Replace(imgUri, newImgPath);
                    }
                }
            }
            return content;
        }
        #endregion

        #region 增加操作=================================
        private async Task<bool> DoAdd(string txtContent)
        {
            bool result = false;
            NetCoreCMS.Models.Article model = new NetCoreCMS.Models.Article();

            model.channel_id = this.channel_id;
            model.shop_id = CMSRequest.GetFormInt("ddlShopId", 0,HttpContext);
            model.category_id = CMSRequest.GetFormInt("ddlCategoryId", 0,HttpContext);
            model.title = CMSRequest.GetFormString("txtTitle",HttpContext).Trim();
            model.call_index = CMSRequest.GetFormString("txtCall_Index", HttpContext).Trim();
            model.link_url = CMSRequest.GetFormString("txtLinkUrl", HttpContext).Trim();
            model.img_url = CMSRequest.GetFormString("txtImgUrl", HttpContext);
            model.seo_title = CMSRequest.GetFormString("txtSeoTitle", HttpContext).Trim();
            model.seo_keywords = CMSRequest.GetFormString("txtSeoKeywords", HttpContext).Trim();
            model.seo_description = CMSRequest.GetFormString("txtSeoDescription", HttpContext).Trim();
            //内容摘要提取内容前255个字符
            if (string.IsNullOrEmpty(CMSRequest.GetFormString("txtZhaiyao",HttpContext).Trim()))
            {
                model.zhaiyao = Utils.DropHTML(txtContent, 255);
            }
            else
            {
                model.zhaiyao = Utils.DropHTML(Request.Form["txtZhaiyao"], 255);
            }
            //是否将编辑器远程图片保存到本地
            if (sysConfig.fileremote == 1)
            {
                model.content = AutoRemoteImageSave(txtContent);
            }
            else
            {
                model.content = txtContent;
            }
            model.sort_id = CMSRequest.GetFormInt("txtSortId",99,HttpContext);
            model.click = CMSRequest.GetFormInt("txtClick", 0, HttpContext); 

            model.is_msg = CMSRequest.GetFormString("cblItem_0", HttpContext).ToLower().IndexOf("true") >= 0 ? 1 : 0;
            model.is_top = CMSRequest.GetFormString("cblItem_1", HttpContext).ToLower().IndexOf("true") >= 0 ? 1 : 0;
            model.is_red = CMSRequest.GetFormString("cblItem_2", HttpContext).ToLower().IndexOf("true") >= 0 ? 1 : 0;
            model.is_hot = CMSRequest.GetFormString("cblItem_3", HttpContext).ToLower().IndexOf("true") >= 0 ? 1 : 0;
            model.is_slide = CMSRequest.GetFormString("cblItem_4", HttpContext).ToLower().IndexOf("true") >= 0 ? 1 : 0;
            model.is_sys = 1; //管理员发布
            model.user_name = GetAdminInfo().user_name; //获得当前登录用户名
            model.status = CMSRequest.GetFormString("cbStatus", HttpContext).ToLower().IndexOf("true") >= 0 ? GetAdminInfo().is_audit : 2;
            model.add_time = Utils.StrToDateTime(CMSRequest.GetFormString("txtAddTime",HttpContext).Trim());
            if (this.channel_id == 2)
            {
                model.goods_no = CMSRequest.GetFormString("field_control_goods_no", HttpContext).Trim();
                model.stock_quantity = CMSRequest.GetFormInt("field_control_stock_quantity", HttpContext);
                model.market_price = CMSRequest.GetFormDecimal("field_control_market_price", 0, HttpContext);
                model.sell_price = CMSRequest.GetFormDecimal("field_control_sell_price", 0, HttpContext);
                model.pv_price = CMSRequest.GetFormDecimal("field_control_pv_price", 0, HttpContext);
                model.point = CMSRequest.GetFormInt("field_control_point", HttpContext);
                #region 保存规格====================
                //保存商品规格
                string goodsSpecJsonStr = Request.Form["hide_goods_spec_list"];
                List<Article_goods_spec> specList = (List<Article_goods_spec>)JsonHelper.JSONToObject<List<Article_goods_spec>>(goodsSpecJsonStr);
                if (specList != null)
                {
                    model.specs = specList;
                }
                //保存商品信息
                string[] specGoodsIdArr = Request.Form["hide_goods_id"];
                string[] specGoodsNoArr = Request.Form["spec_goods_no"];
                string[] specMarketPriceArr = Request.Form["spec_market_price"];
                string[] specSellPriceArr = Request.Form["spec_sell_price"];
                string[] specPVPriceArr = Request.Form["spec_pv_price"];
                string[] specStockQuantityArr = Request.Form["spec_stock_quantity"];
                string[] specSpecIdsArr = Request.Form["hide_spec_ids"];
                string[] specTextArr = Request.Form["hide_spec_text"];
                string[] specGroupPriceArr = Request.Form["hide_group_price"];
                if (specGoodsIdArr != null && specGoodsNoArr != null && specMarketPriceArr != null && specSellPriceArr != null && specStockQuantityArr != null
                    && specSpecIdsArr != null && specTextArr != null && specGroupPriceArr != null
                    && specGoodsIdArr.Length > 0 && specGoodsNoArr.Length > 0 && specMarketPriceArr.Length > 0 && specSellPriceArr.Length > 0
                    && specStockQuantityArr.Length > 0 && specSpecIdsArr.Length > 0 && specTextArr.Length > 0 && specGroupPriceArr.Length > 0)
                {
                    List<Article_goods> goodsList = new List<Article_goods>();
                    for (int i = 0; i < specGoodsNoArr.Length; i++)
                    {
                        List<User_group_price> groupList = new List<User_group_price>();
                        if (!string.IsNullOrEmpty(specGroupPriceArr[i]))
                        {
                            groupList = (List<User_group_price>)JsonHelper.JSONToObject<List<User_group_price>>(specGroupPriceArr[i]);
                        }
                        goodsList.Add(new Article_goods
                        {
                            goods_no = specGoodsNoArr[i],
                            spec_ids = specSpecIdsArr[i],
                            spec_text = specTextArr[i],
                            stock_quantity = Utils.StrToInt(specStockQuantityArr[i], 0),
                            market_price = Utils.StrToDecimal(specMarketPriceArr[i], 0),
                            sell_price = Utils.StrToDecimal(specSellPriceArr[i], 0),
                            pv_price = Utils.StrToDecimal(specPVPriceArr[i], 0),
                            group_prices = groupList
                        });
                    }
                    model.goods = goodsList;
                }
                #endregion

                #region 保存相册====================
                //检查是否有自定义图片
                if (Request.Form["txtImgUrl"].FirstOrDefault().Trim() == "")
                {
                    model.img_url = Request.Form["hidFocusPhoto"];
                }
                string[] albumArr = Request.Form["hid_photo_name"];
                string[] remarkArr = Request.Form["hid_photo_remark"];
                if (albumArr != null && albumArr.Length > 0)
                {
                    List<Article_albums> ls = new List<Article_albums>();
                    for (int i = 0; i < albumArr.Length; i++)
                    {
                        string[] imgArr = albumArr[i].Split('|');
                        if (imgArr.Length == 3)
                        {
                            if (!string.IsNullOrEmpty(remarkArr[i]))
                            {
                                ls.Add(new Article_albums { original_path = imgArr[1], thumb_path = imgArr[2], remark = remarkArr[i] });
                            }
                            else
                            {
                                ls.Add(new Article_albums { original_path = imgArr[1], thumb_path = imgArr[2] });
                            }
                        }
                    }
                    model.albums = ls;
                }
                #endregion
            }
            if(this.channel_id==1)//新闻情况下检测call_index
            {
                int callindex = _article.GetList(1, "where call_index='" + model.call_index + "'", "id asc").Count;
                if (callindex > 0 && !string.IsNullOrEmpty(model.call_index))
                    return false;
            }
            if (_article.Add(model) > 0)
            {
                await AddAdminLog(CMSEnums.ActionEnum.Add.ToString(), "添加内容:" + model.title); //记录日志
                result = true;
            }
            return result;
        }
        #endregion

        #region 修改操作=================================
        [HttpPost]
        private async Task<bool> DoEdit(int _id, string txtContent)
        {
            bool result = false;
            NetCoreCMS.Models.Article model = _article.GetModel(_id);
            model.shop_id = CMSRequest.GetFormInt("ddlShopId", 0, HttpContext);
            model.category_id = CMSRequest.GetFormInt("ddlCategoryId", 0, HttpContext);
            model.title = CMSRequest.GetFormString("txtTitle", HttpContext).Trim();
            model.call_index = CMSRequest.GetFormString("txtCall_Index", HttpContext).Trim();
            model.link_url = CMSRequest.GetFormString("txtLinkUrl", HttpContext).Trim();
            model.img_url = CMSRequest.GetFormString("txtImgUrl", HttpContext);
            model.seo_title = CMSRequest.GetFormString("txtSeoTitle", HttpContext).Trim();
            model.seo_keywords = CMSRequest.GetFormString("txtSeoKeywords", HttpContext).Trim();
            model.seo_description = CMSRequest.GetFormString("txtSeoDescription", HttpContext).Trim();
            //内容摘要提取内容前255个字符
            if (string.IsNullOrEmpty(CMSRequest.GetFormString("txtZhaiyao", HttpContext).Trim()))
            {
                model.zhaiyao = Utils.DropHTML(txtContent, 255);
            }
            else
            {
                model.zhaiyao = Utils.DropHTML(Request.Form["txtZhaiyao"], 255);
            }
            //是否将编辑器远程图片保存到本地
            if (sysConfig.fileremote == 1)
            {
                model.content = AutoRemoteImageSave(txtContent);
            }
            else
            {
                model.content = txtContent;
            }
            model.sort_id = CMSRequest.GetFormInt("txtSortId", 99, HttpContext);
            model.click = CMSRequest.GetFormInt("txtClick", 0, HttpContext);

            model.is_msg = CMSRequest.GetFormString("cblItem_0", HttpContext).ToLower().IndexOf("true") >= 0 ? 1 : 0;
            model.is_top = CMSRequest.GetFormString("cblItem_1", HttpContext).ToLower().IndexOf("true") >= 0 ? 1 : 0;
            model.is_red = CMSRequest.GetFormString("cblItem_2", HttpContext).ToLower().IndexOf("true") >= 0 ? 1 : 0;
            model.is_hot = CMSRequest.GetFormString("cblItem_3", HttpContext).ToLower().IndexOf("true") >= 0 ? 1 : 0;
            model.is_slide = CMSRequest.GetFormString("cblItem_4", HttpContext).ToLower().IndexOf("true") >= 0 ? 1 : 0;
            model.status = CMSRequest.GetFormString("cbStatus", HttpContext).ToLower().IndexOf("true") >= 0 ? GetAdminInfo().is_audit : 2;
            model.add_time = Utils.StrToDateTime(CMSRequest.GetFormString("txtAddTime", HttpContext).Trim());
            model.update_time = DateTime.Now;
            if (this.channel_id == 2)
            {
                model.goods_no = CMSRequest.GetFormString("field_control_goods_no", HttpContext).Trim();
                model.stock_quantity = CMSRequest.GetFormInt("field_control_stock_quantity", HttpContext);
                model.market_price = CMSRequest.GetFormDecimal("field_control_market_price", 0, HttpContext);
                model.sell_price = CMSRequest.GetFormDecimal("field_control_sell_price", 0, HttpContext);
                model.pv_price = CMSRequest.GetFormDecimal("field_control_pv_price", 0, HttpContext);
                model.point = CMSRequest.GetFormInt("field_control_point", HttpContext);
                #region 保存规格====================
                if (true)
                {
                    //保存商品规格
                    string goodsSpecJsonStr = Request.Form["hide_goods_spec_list"];
                    List<Article_goods_spec> specList = (List<Article_goods_spec>)JsonHelper.JSONToObject<List<Article_goods_spec>>(goodsSpecJsonStr);
                    if (specList != null)
                    {
                        model.specs = specList;
                        model.goods = new List<Article_goods>();
                    }
                    //保存商品信息
                    string[] specGoodsIdArr = Request.Form["hide_goods_id"];
                    string[] specGoodsNoArr = Request.Form["spec_goods_no"];
                    string[] specMarketPriceArr = Request.Form["spec_market_price"];
                    string[] specSellPriceArr = Request.Form["spec_sell_price"];
                    string[] specPVPriceArr = Request.Form["spec_pv_price"];
                    string[] specStockQuantityArr = Request.Form["spec_stock_quantity"];
                    string[] specSpecIdsArr = Request.Form["hide_spec_ids"];
                    string[] specTextArr = Request.Form["hide_spec_text"];
                    string[] specGroupPriceArr = Request.Form["hide_group_price"];
                    if (specGoodsIdArr != null && specGoodsNoArr != null && specMarketPriceArr != null && specSellPriceArr != null && specStockQuantityArr != null
                        && specSpecIdsArr != null && specTextArr != null && specGroupPriceArr != null
                        && specGoodsIdArr.Length > 0 && specGoodsNoArr.Length > 0 && specMarketPriceArr.Length > 0 && specSellPriceArr.Length > 0
                        && specStockQuantityArr.Length > 0 && specSpecIdsArr.Length > 0 && specTextArr.Length > 0 && specGroupPriceArr.Length > 0)
                    {
                        List<Article_goods> goodsList = new List<Article_goods>();
                        for (int i = 0; i < specGoodsNoArr.Length; i++)
                        {
                            List<User_group_price> groupList = new List<User_group_price>();
                            if (!string.IsNullOrEmpty(specGroupPriceArr[i]))
                            {
                                groupList = (List<User_group_price>)JsonHelper.JSONToObject<List<User_group_price>>(specGroupPriceArr[i]);
                            }
                            goodsList.Add(new Article_goods
                            {
                                id = Utils.StrToInt(specGoodsIdArr[i], 0),
                                article_id = model.id,
                                goods_no = specGoodsNoArr[i],
                                spec_ids = specSpecIdsArr[i],
                                spec_text = specTextArr[i],
                                stock_quantity = Utils.StrToInt(specStockQuantityArr[i], 0),
                                market_price = Utils.StrToDecimal(specMarketPriceArr[i], 0),
                                sell_price = Utils.StrToDecimal(specSellPriceArr[i], 0),
                                pv_price = Utils.StrToDecimal(specPVPriceArr[i], 0),
                                group_prices = groupList
                            });
                        }
                        model.goods = goodsList;
                    }
                }
                #endregion

                #region 保存相册====================
                //检查是否有自定义图片
                if (Request.Form["txtImgUrl"].FirstOrDefault().Trim() == "")
                {
                    model.img_url = Request.Form["hidFocusPhoto"];
                }
                if (model.albums != null)
                {
                    model.albums.Clear();
                }
                string[] albumArr = Request.Form["hid_photo_name"];
                string[] remarkArr = Request.Form["hid_photo_remark"];
                if (albumArr != null)
                {
                    List<Article_albums> ls = new List<Article_albums>();
                    for (int i = 0; i < albumArr.Length; i++)
                    {
                        string[] imgArr = albumArr[i].Split('|');
                        int img_id = Utils.StrToInt(imgArr[0], 0);
                        if (imgArr.Length == 3)
                        {
                            if (!string.IsNullOrEmpty(remarkArr[i]))
                            {
                                ls.Add(new Article_albums { id = img_id, article_id = _id, original_path = imgArr[1], thumb_path = imgArr[2], remark = remarkArr[i] });
                            }
                            else
                            {
                                ls.Add(new Article_albums { id = img_id, article_id = _id, original_path = imgArr[1], thumb_path = imgArr[2] });
                            }
                        }
                    }
                    model.albums = ls;
                }
                #endregion
            }
            if (_article.Update(model, _env.WebRootPath))
            {
                await AddAdminLog(CMSEnums.ActionEnum.Edit.ToString(), "修改内容:" + model.title); //记录日志
                result = true;
            }
            return result;
        }
        #endregion
    }
}
